<template>
    <div class="login-container">
        <el-card class="login-card">
            <el-tabs v-model="activeTab" stretch>
                <el-tab-pane label="登录" name="login">
                    <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="loginForm.username" autocomplete="off">
                                <template #prefix>
                                    <el-icon>
                                        <User />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="loginForm.password" type="password" autocomplete="off">
                                <template #prefix>
                                    <el-icon>
                                        <Lock />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="验证码">
                            <el-input v-model="loginForm.code" type="password" autocomplete="off">
                                <template #append>
                                    <img style="width: 100px;height:100px" @click="resetCode" :src="codeUrl" alt="">
                                </template>
                            </el-input>

                        </el-form-item>

                        <el-form-item>
                            <div class="login-btn-group">
                                <el-button type="primary" @click="handleLogin" class="login-btn">直接登录</el-button>
                                <el-button type="warning" @click="handleGuestLogin" class="guest-btn">游客登录</el-button>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="注册" name="register">
                    <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="80px">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="registerForm.username" autocomplete="off">
                                <template #prefix>
                                    <el-icon>
                                        <User />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="registerForm.password" type="password" autocomplete="off">
                                <template #prefix>
                                    <el-icon>
                                        <Lock />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input v-model="registerForm.confirmPassword" type="password" autocomplete="off">
                                <template #prefix>
                                    <el-icon>
                                        <Lock />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleRegister">注册</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import router from '@/router';
import { commonAjax } from '@/util/request.js'
const activeTab = ref('login');

const loginForm = reactive({
    username: '宋开国123',
    password: '123123',
    code: ''
});
const loginRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};
const loginFormRef = ref();
const codeUrl = ref<string>(`${Config.serverUrl}/login/code`)
const resetCode = () => codeUrl.value = codeUrl.value + '?' + Math.random()
const handleLogin = () => {
    (loginFormRef.value as any).validate((valid: boolean) => {
        if (valid) {
            let _this = this;
            return new Promise((resolve, reject) => {
                commonAjax({
                    url: `${Config.serverUrl}/login/login`,
                    data: {
                        ...loginForm
                    },
                    headers: {
                        'content-type': 'application/json'
                    }
                })
                    .then((result) => {
                        console.log('register', result.data);
                        if (result && result.code == 200) {
                            ElMessage.success('登录成功');
                            localStorage.setItem('userInfo', JSON.stringify(result.data))
                            localStorage.setItem('isLogin', '1')
                            setTimeout(() => {
                                router.push('/index');
                            }, 1000)

                        } else {
                            ElMessage.warning(result.message)

                        }
                    })
                    .catch((err) => {

                        ElMessage.warning(err.message)
                    });
            })

        }
    });
};
const handleRegister = () => {
    (registerFormRef.value as any).validate((valid: boolean) => {
        if (valid) {
            let _this = this;
            return new Promise((resolve, reject) => {
                commonAjax({
                    url: `${Config.serverUrl}/login/register`,
                    data: {
                        ...loginForm
                    },
                })
                    .then((result) => {
                        console.log('register', result.data);
                        if (result && result.code == 200) {
                            ElMessage.success('注册成功');
                            setTimeout(() => {
                                router.push('/index');
                            }, 1000)

                        } else {
                            ElMessage.warning(result.message)

                        }
                    })
                    .catch((err) => {

                        ElMessage.warning(err.message)
                    });
            })
            ElMessage.success('注册成功（示例）');
            activeTab.value = 'login';
        }
    });
};
const registerForm = reactive({
    username: '',
    password: '',
    confirmPassword: ''
});
const registerRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (_: any, value: string) => value === registerForm.password,
            message: '两次输入的密码不一致',
            trigger: 'blur'
        }
    ]
};
const registerFormRef = ref();



const randomGuestName = () => {
    const prefix = '游客';
    const randomStr = Math.random().toString(36).substring(2, 8);
    return `${prefix}_${randomStr}`;
};

const handleGuestLogin = () => {
    loginForm.username = randomGuestName();
    loginForm.password = '';
    ElMessage.success(`以${loginForm.username}身份登录（游客模式）`);
    // 这里可以直接跳转主页或执行登录后的逻辑
    router.push('/index');
};
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    background: linear-gradient(135deg, #e0eafc 0%, #cfdef3 100%);
}

.login-card {
    width: 400px;
    padding: 32px 24px 16px 24px;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
    border-radius: 16px;
    background: #fff;
    border: none;
}

.el-tabs__item {
    font-size: 18px;
    font-weight: 500;
}

.el-form {
    margin-top: 24px;
}

.el-form-item {
    margin-bottom: 24px;
}

.el-input__wrapper {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(31, 38, 135, 0.05);
}

.login-btn-group {
    display: flex;
    gap: 16px;
    width: 100%;
    justify-content: center;
}

.login-btn {
    width: 50%;
    font-size: 16px;
    font-weight: 500;
    border-radius: 8px;
    background-color: #2193b0;
    border: none;
    transition: all 0.3s ease;
}

.guest-btn {
    width: 50%;
    font-size: 16px;
    font-weight: 500;
    border-radius: 8px;
    background-color: #f7971e;
    color: #fff;
    border: none;
    transition: all 0.3s ease;
}

.login-btn:hover {
    background-color: #6dd5ed;
}

.guest-btn:hover {
    background-color: #ffd200;
}
</style>
